package com.czy.owner.ui.information;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.czy.owner.R;
import com.czy.owner.api.CollectionApi;
import com.czy.owner.api.OwnerInfoIsCollectApi;
import com.czy.owner.api.PriceRatioInfoDataApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.PriceRadioModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.AssetsFileUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.ShareUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.google.gson.JsonObject;
import com.iflytek.thirdparty.P;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * Created by wangyang on 2017/5/16 0016.
 * 比价活动详情
 */

public class PriceRatioDetailActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    private String title;
    private String content;
    private String imgUrl;
    private int infoId;
    private String collectType = "carInfo";
    MenuItem itemCollect;
    private String url;
    private String postDate;
    private String session;
    private String shareUrl;
    private boolean mIsCollect;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(getIntent().getStringExtra("title"));
        session = UserHelper.getInstance().getSession(PriceRatioDetailActivity.this);
        infoId = getIntent().getIntExtra("infoId",0);
        url = Constants.APP_API_BASE + Constants.OWN_INFO_INFOCONTENT;
        postDate = "session=" + session + "&infoId=" + infoId;
        WebSettings ws = webView.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setUseWideViewPort(false);  //将图片调整到适合webview的大小
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webView.postUrl(url, postDate.getBytes());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    myProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.GONE == myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }


        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                MyLog.d("yang", request.getUrl().toString());
                Pattern p = Pattern.compile("pub/goodsView\\?goodsId=(\\d*?)$");
                Matcher m = p.matcher(request.getUrl().toString());
                while (m.find()) {
                    final String goodsId = m.group(1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webView.stopLoading();
                            webView.postUrl(url, postDate.getBytes());
                            Intent intent = new Intent(PriceRatioDetailActivity.this, GoodsDetailActivity.class);
                            intent.putExtra("goodsId", Integer.parseInt(goodsId));
                            intent.putExtra("mFromType", Constants.GOODSSOURCE_RATE);
                            intent.putExtra("mFromTypeId", "0");
                            MyLog.d("yang", "goodsId==" + goodsId);
                            startActivity(intent);
                        }
                    });
                    return null;
                }
                return super.shouldInterceptRequest(view, request);
            }

        });

    }


//    获取分享数据
     public void getOwnInfoData(){
         PriceRatioInfoDataApi priceRatioInfoDataApi = new PriceRatioInfoDataApi(new HttpOnNextListener<PriceRadioModel>() {
             @Override
             public void onNext(PriceRadioModel data) {
                 title = data.getInfo().getTitle();
                 content = data.getInfo().getContent();
                 imgUrl = data.getInfo().getCoverUrl();
                 mIsCollect = data.getInfo().isIsCollect();
                 if (UserHelper.getInstance().isLogined()) {
                     if (mIsCollect) {
                         itemCollect.setIcon(R.mipmap.icon_webview_collection_select);
                     } else {
                         itemCollect.setIcon(R.mipmap.icon_webview_collection_normal);
                     }
                 }
             }

             @Override
             public void onError(Throwable e) {
                 super.onError(e);
                 PhoneUtils.ShowToastMessage(PriceRatioDetailActivity.this,e.getMessage());

             }
         },PriceRatioDetailActivity.this);
         priceRatioInfoDataApi.setSession(session);
         priceRatioInfoDataApi.setInfoId(infoId + "");
         HttpManager httpManager = HttpManager.getInstance();
         httpManager.doHttpDeal(priceRatioInfoDataApi);
     }


    @Override
    protected void updateViews() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_information_detail_top, menu);
        itemCollect = menu.findItem(R.id.img_collection);
        getOwnInfoData();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon_share:
                if (TextUtils.isEmpty(imgUrl)) {
                    try {
                        AssetsFileUtils.getImageFromAssetsFile(PriceRatioDetailActivity.this, "owner_share_icon.png");
                    } catch (Exception e) {

                    }
                }
                shareUrl = Constants.APP_API_BASE + Constants.STO_INTO_SHARE + "?infoId=" + infoId;
                ShareUtils.showShare(this, null, false, shareUrl, PhoneUtils.delHTMLTag(title), PhoneUtils.delHTMLTag(content), imgUrl, shareUrl);
                break;
            case R.id.img_collection:
                if (checkLoginState()) {
                    if (mIsCollect) {
                        requestCollect(collectType, infoId + "", "delCollect", false);
                        itemCollect.setIcon(R.mipmap.icon_webview_collection_normal);
                    } else {
                        requestCollect(collectType, infoId + "", "", true);
                        itemCollect.setIcon(R.mipmap.icon_webview_collection_select);
                    }
                }
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }

    private void requestCollect(final String collectType, String collectTypeId, String type, final boolean isMCollect) {
        CollectionApi collectionApi = new CollectionApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String o) {
                if (isMCollect) {
                    PhoneUtils.ShowToastMessage(PriceRatioDetailActivity.this, "收藏成功");
                    mIsCollect = true;

                } else {
                    PhoneUtils.ShowToastMessage(PriceRatioDetailActivity.this, "取消成功");
                    mIsCollect = false;

                }
                RxBus.getDefault().post(Constants.COLLECTION, new CommonEvent(collectType));


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                PhoneUtils.ShowToastMessage(PriceRatioDetailActivity.this, e.getMessage());
            }
        }, this);
        collectionApi.setSession(UserHelper.getInstance().getSessionInfoModel(PriceRatioDetailActivity.this).getSession());
        collectionApi.setCollectType(collectType);
        collectionApi.setCollectTypeId(collectTypeId);
        collectionApi.setType(type);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(collectionApi);


    }


}
